<?php

class modTagSearch extends cDycmsClientModule
{
	function __construct($id = null){
		
		parent::__construct('Search');
		
		$q = dyPostOrGet('$$modTagSearch-query');
		
		if($id == null){
			$id = uiGetModuleId('modTagSearch');
		}else{
			
			if($q != ''){
				
				//
				// Perform the search
				//
				
				$search = new cDycmsQuery();
				$search->AddArray(array('tag' => '*'.$q.'*'));
				$n = $search->Execute(false, true);
				
				if($n == 0){
					$this->AddChild("No results for tags matching '$q'");
				}else{
					$this->AddChild("Displaying $n result(s)");

					for($i = 0; $i < $n; $i++){
						$this->AddChild($item = new cUiLayer(array(
							'class' => 'modTagSearch-result')));
						
						$search->Render($item, $i);
					}
				}
				
				cUiPage::GetInst()->sTitle = "Searching for '$q'";
			}
		}
		
		$this->AddChild($f = new cUiForm(array(
			'action' => dyViewerUrl('Module', $id),
			'method' => 'GET'
		), array(
			// HACK: this is frontend dependent. Abstract this out.
			'saveData' => array(
				'$action' => 'view',
				'$clsid' => 'Module',
				'$id' => $id
			)
		)));
		
		$f->AddChild(new cUiTextBox(array(
			'name' => '$$modTagSearch-query',
			'value' => $q)));
		$f->AddChild(new cUiButton(array(
			'name' => '$$modTagSearch-action',
			'value' => 'search'
		), 'Search', 'magnifier'));
	}
}

class cUiTagZone extends cUiSection
{
	function __construct($zTags, $zCounts = null){
		static $idTs;
		if(!isset($idTs)) $idTs = uiGetModuleId('modTagSearch');
		
		$n = count($zTags);
		
		if(is_array($zCounts)){
			$avg = 0;
			for($i = 0; $i < $n; $i++)
				$avg += $zCount[$i];
			$avg /= $n;
			for($i = 0; $i < $n; $i++){
				$zCount[$i] = intval(($zCount[$i] / $avg) * 4);
				if($zCount[$i] > 7)
					$zCount[$i] = 7;
				else if($zCount[$i] < 1)
					$zCount[$i] = 1;
			}
		}else{
			$zCounts = array_fill(0, $n, 4);
		}
		
		parent::__construct($n == 1 ? 'One Tag' : $n.' Tags');
		
		$q = trim(dyPostOrGet('$$modTagSearch-query'));
		
		if($n > 0){
			for($i = 0; $i < ($n - 1); $i++){
				$this->AddChild(new cHtmlHyperlink(
					dyViewerUrl('Module', $idTs, array(
						'$$modTagSearch-action' => 'search',
						'$$modTagSearch-query' => $zTags[$i]
					)), str_ireplace($q,"<b>$q</b>",$zTags[$i]), array(
						'class' => $zCount[$i]
					)));
				$this->AddChild(', ');
			}
			$this->AddChild(new cHtmlHyperlink(
				dyViewerUrl('Module', $idTs, array(
					'$$modTagSearch-action' => 'search',
					'$$modTagSearch-query' => $zTags[$i]
				)), str_ireplace($q,"<b>$q</b>",$zTags[$i]), array(
					'class' => $zCount[$i]
				)));
		}else{
			$this->AddChild('Not tagged');
		}
	}
}
